package com.rp.admin.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.rp.admin.serivce.AdminUserService;
import com.rp.bo.AdminLoginBO;
import com.rp.bo.NewAdminBO;
import com.rp.news.common.*;
import com.rp.news.enums.FaceVerifyType;
import com.rp.news.exception.GraceException;
import com.rp.news.util.CommonUtil;
import com.rp.news.util.RedisOperator;
import com.rp.news.util.extent.FaceVerifyUtils;
import com.rp.pojo.AdminUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@Api(value = "管理员admin相关接口", tags = {"管理员admin相关接口 api文档"})
@RequestMapping("/adminMng")
@Slf4j
public class AdminMngController {


    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private RedisOperator redis;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private FaceVerifyUtils faceVerifyUtils;

    @Autowired
    private CommonUtil commonUtil;


    @ApiOperation(value = "管理员登录接口", notes = "管理员登录接口", httpMethod = "POST")
    @PostMapping("/adminLogin")
    public Result adminLogin(@RequestBody AdminLoginBO adminLoginBO, HttpServletRequest request, HttpServletResponse response) {

        log.info("管理员登录接口 adminLoginBO = {}", JSON.toJSONString(adminLoginBO));
        //参数校验
        if (StrUtil.isBlank(adminLoginBO.getUsername())) {
            return Result.errorCustom(ResponseStatusEnum.PARAM_ERROR);
        }

        //查询用户信息
        AdminUser adminUser = adminUserService.queryAdminUserByUsername(adminLoginBO.getUsername());
        log.info("管理员登录接口 adminUser = {}", JSON.toJSONString(adminUser));
        if (adminUser == null) {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }

        boolean checkpw = BCrypt.checkpw(adminLoginBO.getPassword(), adminUser.getPassword());
        log.info("管理员登录接口 checkpw = {}", checkpw);
        if (checkpw) {
            doAdimLoginSettings(adminUser, request, response);
            return Result.ok();
        }
        return Result.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
    }

    @ApiOperation(value = "admin用户退出登录", notes = "admin用户退出登录", httpMethod = "POST")
    @PostMapping("/adminLogout")
    public Result adminLogout(@RequestParam("adminId") String adminId, HttpServletRequest request, HttpServletResponse response) {
        redis.del(RedisCommon.REDIS_ADMIN_TOKEN + ":" + adminId);
        commonUtil.deleteCookie(request, response, "atoken");
        commonUtil.deleteCookie(request, response, "aid");
        commonUtil.deleteCookie(request, response, "aname");
        return Result.ok();
    }

    @ApiOperation(value = "查询admin用户是否存在", notes = "查询admin用户是否存在", httpMethod = "POST")
    @PostMapping("/adminIsExist")
    public Result adminIsExist(String username) {
        checkAdminExist(username);
        return Result.ok();
    }

    @ApiOperation(value = "创建admin用户", notes = "创建admin用户", httpMethod = "POST")
    @PostMapping("/addNewAdmin")
    public Result addNewAdmin(@RequestBody NewAdminBO newAdminBO) {
        //查询用户信息
        AdminUser adminUser = adminUserService.queryAdminUserByUsername(newAdminBO.getUsername());
        if (adminUser != null) {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_USERNAME_EXIST_ERROR);
        }
        adminUserService.createAdminUser(newAdminBO);
        return Result.ok();
    }

    @ApiOperation(value = "查询admin用户列表", notes = "查询admin用户列表", httpMethod = "POST")
    @PostMapping("/getAdminList")
    public Result getAdminList(@RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize) {
        log.info("查询admin用户列表");
        if (page == null) {
            page = NewsCommon.COMMON_START_PAGE;
        }
        if (pageSize == null) {
            pageSize = NewsCommon.COMMON_PAGE_SIZE;
        }
        PagedResult pageResult = adminUserService.queryAdminList(page, pageSize);
        log.info("查询admin用户列表,返回结果 pageResult = {}", JSONUtil.toJsonStr(pageResult));
        return Result.ok(pageResult);
    }


    @ApiOperation(value = "admin管理员人脸登录", notes = "admin管理员人脸登录", httpMethod = "POST")
    @PostMapping("/adminFaceLogin")
    public Result adminFaceLogin(@RequestBody AdminLoginBO adminLoginBO, HttpServletRequest request, HttpServletResponse response) {
        if (StrUtil.isBlank(adminLoginBO.getUsername())) {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_USERNAME_NULL_ERROR);
        }
        if (StrUtil.isBlank(adminLoginBO.getImg64())) {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }
        AdminUser adminUser = adminUserService.queryAdminUserByUsername(adminLoginBO.getUsername());

        String url = "http://www.rpnews.com:7007/fsservice/fs/readFace64InGridFS?faceId=" + adminUser.getFaceId();
        ResponseEntity<Result> forEntity = restTemplate.getForEntity(url, Result.class);
        Result body = forEntity.getBody();
        String base64 = (String) body.getData();

        //调用阿里云ai进行人脸对比
        //boolean b = faceVerifyUtils.faceVerify(FaceVerifyType.BASE64.type, adminLoginBO.getImg64(), base64, 60);
        //todo
        boolean b=true;
        if (!b) {
            return Result.errorCustom(ResponseStatusEnum.ADMIN_FACE_LOGIN_ERROR);
        }

        doAdimLoginSettings(adminUser, request, response);
        return Result.ok();
    }


   //=============================================私有方法=========================================================



    private void checkAdminExist(String username) {
        AdminUser adminUser = adminUserService.queryAdminUserByUsername(username);
        if (adminUser == null) {
            GraceException.display(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }
    }


    /**
     * 用户admin用户登录后信息的保存
     *
     * @param adminUser
     * @param request
     * @param response
     */
    private void doAdimLoginSettings(AdminUser adminUser, HttpServletRequest request, HttpServletResponse response) {
        String atoken = IdUtil.fastSimpleUUID();
        redis.set(RedisCommon.REDIS_ADMIN_TOKEN + ":" + adminUser.getId(), atoken, NewsCommon.COOKIE_MONTH);
        commonUtil.setCookie(request, response, "atoken", atoken, NewsCommon.COOKIE_MONTH);
        commonUtil.setCookie(request, response, "aid", adminUser.getId(), NewsCommon.COOKIE_MONTH);
        commonUtil.setCookie(request, response, "aname", adminUser.getAdminName(), NewsCommon.COOKIE_MONTH);
    }


}
